﻿using System.Runtime.InteropServices;
using System;



namespace System  // Placed in the system namespace to avoid requiring PDOFX imports
{
    public static class GuidHelperDuct
    {
        public static bool IsNullOrEmpty(this Guid? guid)
        {
            return (guid == null || guid == Guid.Empty);
        }

        public static bool IsNullOrEmpty(this Guid guid)
        {
            return (guid == null || guid == Guid.Empty);
        }

    }
}

namespace PDO.Utilities
{
    public static class GuidHelper
    {
        /// <summary>
        /// Converts the string representation of a GUID to its System.Guid equivalent.  A return value
        /// indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="s">A string containing the GUID to convert.</param>
        /// <param name="value">When this method returns, contains the System.Guid value equivalent to
        /// the GUID contained in s, if the conversion succeeded, or Guid.Empty if the conversion
        /// failed. The conversion fails if the s parameter is null or is not of the correct format. 
        /// This parameter is passed uninitialized.</param>
        /// <returns>true if s was converted successfully; otherwise, false.</returns>
        public static bool TryParse(string s, out Guid value)
        {
            if (string.IsNullOrEmpty(s))
            {
                value = Guid.Empty;
                return false;
            }


            // CLSIDFromString requires enclosing curly braces on its GUIDs.
            if (!s.StartsWith("{"))
            {
                s = "{" + s;
            }
            if (!s.EndsWith("}"))
            {
                s += "}";
            }


            int result = CLSIDFromString(s, out value);
            if (result >= 0)
            {
                return true;
            }
            else
            {
                value = Guid.Empty;
                return false;
            }
        }


        /// <summary>
        /// This function converts a string generated by the StringFromCLSID function back into the
        /// original class identifier.
        /// </summary>
        /// <param name="sz">String that represents the class identifier</param>
        /// <param name="clsid">On return will contain the class identifier</param>
        /// <returns>
        /// Positive or zero if class identifier was obtained successfully
        /// Negative if the call failed
        /// </returns>
        [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
        private static extern int CLSIDFromString(string sz, out Guid clsid);
    }
}